package com.alks.pad.service.serviceImpl.stitchAccount;


import com.alks.common.aop.AutoPageAop;
import com.alks.common.utils.beanutils.ObjectUtils;
import com.alks.entity.data.entity.PadStitchLog;
import com.alks.entity.data.entity.PcStitchLotPriceDetail;
import com.alks.entity.data.entity.PcStitchProdDetail;
import com.alks.entity.data.response.ResponseInfo;
import com.alks.entity.exception.ServiceErrorException;
import com.alks.pad.commom.date.dto.PadUserTokenDto;
import com.alks.pad.commom.date.thread.PadUserIdThread;
import com.alks.pad.data.dto.padCollectUser.PadUserDeptDto;
import com.alks.pad.data.dto.stitch.PcStitchProdDetailDto3;
import com.alks.pad.data.dto.stitch.StitchInventoryDetailDto;
import com.alks.pad.data.dto.stitch.StitchInventoryDto;
import com.alks.pad.data.dto.stitch.StitchProducedSalaryDto;
import com.alks.pad.data.request.stitchAccount.*;
import com.alks.pad.mapper.stitchAccount.StitchMapper;
import com.alks.pad.service.stitchAccount.StitchService;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Slf4j
public class StitchServiceImpl implements StitchService {

    @Autowired
    private StitchMapper stitchInventoryMapper;

    private final RedisTemplate redisTemplate;

    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");


    @Autowired
    public StitchServiceImpl(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    private boolean tryLock(String lockKey, String lockValue, long expireTime, TimeUnit timeUnit) {
        // 尝试设置键值对，如果键不存在则创建并设置过期时间
        Boolean result = redisTemplate.opsForValue().setIfAbsent(lockKey, lockValue, expireTime, timeUnit);
        return Boolean.TRUE.equals(result);
    }

    private void unlock(String lockKey, String lockValue) {
        // 使用 Lua 脚本确保原子性操作，只有当前持有锁的客户端才能删除锁
        String luaScript =
                "if redis.call('get', KEYS[1]) == ARGV[1] then " +
                        "return redis.call('del', KEYS[1]) " +
                        "else " +
                        "return 0 " +
                        "end";
        DefaultRedisScript<Long> script = new DefaultRedisScript<>(luaScript, Long.class);
        redisTemplate.execute(script, Collections.singletonList(lockKey), lockValue);
    }


    /**
     * 针车产值查询查询
     * @param request
     * @return
     */
    @Override
    public ResponseInfo getProducedValue(ProducedValueRequest request) {
        //判断
        if(request.getDeptNo() == null || request.getDeptName() == null){
            return ResponseInfo.error("请选择组别");
        }
        if(request.getMonthAndYear() == null){
            return ResponseInfo.error("请选择月份");
        }

        String companyId = PadUserIdThread.get().getCompanyId();
        List<StitchProducedSalaryDto> list = stitchInventoryMapper.getProducedValue(companyId,request);

        HashMap map = new HashMap<>();
        PageInfo page = new PageInfo(list);
        map.put("total",page.getTotal());
        map.put("list",list);
        return ResponseInfo.ok(map);
    }

    /**
     * 查询员工当月每天的工资
     * @param request
     * @return
     */
    @Override
    public ResponseInfo getEmployeeDailySalary(ProducedValueRequest request) {
        String companyId = PadUserIdThread.get().getCompanyId();
        List<StitchProducedSalaryDto> list = stitchInventoryMapper.getEmployeeDailySalary(companyId,request);

        BigDecimal totalAmt = list.stream()
                .map(StitchProducedSalaryDto::getAmt)
                .filter(Objects::nonNull) // 过滤掉 null 值
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        HashMap map = new HashMap<>();
        PageInfo page = new PageInfo(list);
        map.put("total",page.getTotal());
        map.put("totalAmt",totalAmt);
        map.put("list",list);
        return ResponseInfo.ok(map);
    }

    /**
     * 查询员工当日工序工资
     * @param request
     * @return
     */
    @Override
    public ResponseInfo getEmployeeDailyProcessSalary(ProducedValueRequest request) {
        String companyId = PadUserIdThread.get().getCompanyId();
        List<StitchProducedSalaryDto> list = stitchInventoryMapper.getEmployeeDailyProcessSalary(companyId,request);

        BigDecimal totalAmt = list.stream()
                .map(StitchProducedSalaryDto::getAmt)
                .filter(Objects::nonNull) // 过滤掉 null 值
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        HashMap map = new HashMap<>();
        PageInfo page = new PageInfo(list);
        map.put("total",page.getTotal());
        map.put("totalAmt",totalAmt);
        map.put("list",list);
        return ResponseInfo.ok(map);
    }

    /**
     * 查询员工产量明细
     */
    @Override
    public ResponseInfo getYieldDetails(PcStitchProdDetailRequest1 request) {
        String companyId = PadUserIdThread.get().getCompanyId();
        request.setCompanyId(companyId);
        PageHelper.startPage(request.getPageNum(),request.getPageSize());
        //查询页面上的统计数量
        List<PcStitchProdDetailDto3> list = stitchInventoryMapper.getPcStitchProdDetailList(request);

        //查询页面上的的统计数量
        Integer countSum = stitchInventoryMapper.getPcStitchProdDetailOfQtyCount(request);

        HashMap map = new HashMap<>();
        PageInfo page = new PageInfo(list);
        map.put("total",page.getTotal());
        map.put("totalAmt",countSum);
        map.put("list",list);
        return ResponseInfo.ok(map);
    }

    /**
     * 待报产指令查询
     * @param request
     * @return
     */
    @Override
    public ResponseInfo getNotReportProductDetails(StitchInventoryRequest request) {
        //判断，要选择组别
        if(request.getDeptNo() == null || request.getDeptName() == null){
            return ResponseInfo.error("请选择组别");
        }

        String companyId = PadUserIdThread.get().getCompanyId();
        List<StitchInventoryDto> list = stitchInventoryMapper.getNotReportProductDetails2(companyId,request);
        for (StitchInventoryDto l : list) {
            l.setDeptName(request.getDeptName());
        }

        HashMap map = new HashMap<>();
        PageInfo page = new PageInfo(list);
        map.put("total",page.getTotal());
        map.put("list",list);
        return ResponseInfo.ok(map);
    }

    /**
     * 当日已报产完
     * @param request
     * @return
     */
    @Override
    @AutoPageAop
    public ResponseInfo getReportProductDetails(StitchInventoryRequest request) {

        String companyId = PadUserIdThread.get().getCompanyId();
        List<StitchInventoryDto> resultList = stitchInventoryMapper.getReportProductDetails3(companyId,request);

        HashMap map = new HashMap<>();
        PageInfo page = new PageInfo(resultList);
        map.put("total",page.getTotal());
        map.put("list",resultList);
        return ResponseInfo.ok(map);
    }

    /**
     * 批量报产-》待报工序查询
     * @param request
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo batchReportProduct(List<StitchInventoryDRequest> request) {
        if(ObjectUtils.isEmpty(request)){
            throw  new ServiceErrorException("请选择数据！");
        }
        Set<String> lotNos = new HashSet<>();
        Set<String> dates = new HashSet<>();
        Set<Integer> orderTypes = new HashSet<>();
        int qty = 0;
        for (StitchInventoryDRequest req : request) {
            lotNos.add(req.getLotNo());
            dates.add(req.getSlipDate());
            orderTypes.add(req.getOrderType());
            if (lotNos.size() > 1 || dates.size() > 1 || orderTypes.size() > 1) {
                throw  new ServiceErrorException("不同缴库日期、指令、类型无法合并并批量派工！");
            }
            qty += req.getQty(); //满足条件的一起报产的数量
        }

        String companyId = PadUserIdThread.get().getCompanyId();
        StitchInventoryDRequest d = request.get(0);
        //填充查询条件
        StitchInventoryRequest r = new StitchInventoryRequest();
        BeanUtils.copyProperties(d,r);
        r.setQty(qty);

        //先查这个指令有没有工序建档
        List<PcStitchLotPriceDetail> lotPriceDetails = stitchInventoryMapper.getPcStitchLotPriceDetail(companyId,r);
        if(ObjectUtils.isEmpty(lotPriceDetails)){
            throw  new ServiceErrorException("该指令型体没有工序建档！");
        }

        //待报产工序以及数量
        List<StitchInventoryDetailDto> list = stitchInventoryMapper.getNotReportProcessDetailsByLotNo2(companyId,r);

        if(ObjectUtils.isNotEmpty(list)){
            for (StitchInventoryDetailDto l : list) {
                l.setDeptName(d.getDeptName());
            }
        }

        HashMap map = new HashMap<>();
        PageInfo page = new PageInfo(list);
        map.put("total",page.getTotal());
        map.put("list",list);
        return ResponseInfo.ok(map);
    }

    /**
     * 待报工序查询
     * @param request
     * @return
     */
    @Override
    public ResponseInfo getNotReportProcessDetails(StitchInventoryRequest request) {
        String companyId = PadUserIdThread.get().getCompanyId();
        //先查这个指令有没有工序建档
        List<PcStitchLotPriceDetail> lotPriceDetails = stitchInventoryMapper.getPcStitchLotPriceDetail(companyId,request);
        if(ObjectUtils.isEmpty(lotPriceDetails)){
            return ResponseInfo.error("该指令型体没有工序建档！");
        }

        //待报产工序以及数量
        List<StitchInventoryDetailDto> list = stitchInventoryMapper.getNotReportProcessDetailsByLotNo2(companyId,request);
        if(ObjectUtils.isNotEmpty(list)){
            for (StitchInventoryDetailDto l : list) {
                l.setDeptName(request.getDeptName());
            }
        }

        HashMap map = new HashMap<>();
        PageInfo page = new PageInfo(list);
        map.put("total",page.getTotal());
        map.put("list",list);
        return ResponseInfo.ok(map);
    }

    /**
     * 录入
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo reportProcessByDefineQty(StitchInventoryDetailDRequest2 r) {
        long start = System.currentTimeMillis();
        //判断
        StitchInventoryDetailDRequest request = r.getStitchRequest();
        if(request == null){
            throw  new ServiceErrorException("请选择工序！");
        }
        if(r.getWorkId() == null || r.getWorkName() == null){
            throw  new ServiceErrorException("请选择员工！");
        }
        if(r.getQty4() == 0){
            throw  new ServiceErrorException("请输入报数！");
        }
        if(r.getQty4() > request.getQty3()){
            throw  new ServiceErrorException("报数超出实际！");
        }
        //报产的部门不能为空或者空字符串
        if(r.getDeptNo() == null || r.getDeptName() == null || r.getDeptNo().equals("") || r.getDeptName().equals("") ){
            throw  new ServiceErrorException("报产部门不能为空！");
        }

        //获取当前用户
        PadUserTokenDto padUserTokenDto = PadUserIdThread.get();
        String companyId = padUserTokenDto.getCompanyId();
        String collectUserName = padUserTokenDto.getCollectUserName();
        List<PadUserDeptDto> departmentList = padUserTokenDto.getDepartmentList();
        if(ObjectUtils.isEmpty(departmentList) ){
            throw  new ServiceErrorException("token中没有查到当前登录部门信息") ;
        }
        PadUserDeptDto deptDto = departmentList.get(0);
        String deptNo1 = deptDto.getDeptNo();
        String deptName1 = deptDto.getDeptName();
        request.setDeptNo(deptNo1);
        request.setDeptName(deptName1);

        //上锁
        String lockKey = "lock:stitchProReport:" + companyId + ":" + request.getLotNo() + ":" +
                request.getSlipDate() + ":" + request.getOrderType() + ":" + request.getDeptNo();
        String lockValue = UUID.randomUUID().toString();

        // 设置锁的有效期为1000毫秒（1秒）（假设最大执行时间为200毫秒）
        boolean isLocked = tryLock(lockKey, lockValue, 5, TimeUnit.SECONDS);

        if (!isLocked) {
            throw new ServiceErrorException("系统繁忙，请稍后刷新后再试");
        }

        try {
            // 执行原有业务逻辑...
            // ...
            //1.第一道检查：检查现在已经报产的总数量和最大的版本号
            StitchInventoryDetailDto countFlag = stitchInventoryMapper.getNotReportProcessDetailsByLotNo3(companyId,request);
            if(countFlag == null){
                throw  new ServiceErrorException("数据已更新,请刷新重试");
            }
            if(r.getQty4() > countFlag.getQty3()){
                throw  new ServiceErrorException("数据已更新,报数超出实际,请刷新重试");
            }
            //2.第二道检查：检查乐观锁
            //if (countFlag.getVersion() != request.getVersion()) {
            //    throw  new ServiceErrorException("数据版本已更新,请刷新重试");
            //}

            PcStitchProdDetail detail = new PcStitchProdDetail();
            BeanUtils.copyProperties(request,detail);

            BigDecimal price = request.getPrice();//价格
            BigDecimal qty = BigDecimal.valueOf(r.getQty4());//输入的报数
            BigDecimal amt = (price != null) ? qty.multiply(price) : null; //金额
            detail.setQty(qty);
            detail.setPrice(price);
            detail.setAmt(amt);

            detail.setWorkId(r.getWorkId());
            detail.setWorkName(r.getWorkName());
            detail.setWorkDeptNo(r.getDeptNo());
            detail.setWorkDeptName(r.getDeptName());
            detail.setDeptNo(deptNo1);
            detail.setDeptName(deptName1);

//        detail.setSysDate(LocalDateTime.now());
            detail.setSysUser(collectUserName);
            detail.setCfmFlag("Y");
//        detail.setCfmDate(String.valueOf(LocalDateTime.now()));
            detail.setCfmUser(PadUserIdThread.get().getCollectUserName());
            detail.setCompanyId(companyId);
            detail.setSlipDate(request.getSlipDate());
            detail.setSeqNo(BigDecimal.valueOf(request.getSeqNo()));
            if(request.getOrderType2() != null){
                if (request.getOrderType2().equals("正单")) {
                    detail.setOrderType(BigDecimal.valueOf(0));
                }else if(request.getOrderType2().equals("补单")){
                    detail.setOrderType(BigDecimal.valueOf(1));
                }
            }else{
                throw  new ServiceErrorException("请检查指令类型！");
            }

            int count = 0;
            try {
                count = stitchInventoryMapper.addPcStitchProdDetail(detail);
            }catch(Exception e){
                throw  new ServiceErrorException("请刷新重试");
                //e.printStackTrace();
            }

            /*更新 PcStitchProdDetail 版本号*/
            stitchInventoryMapper.updatePcStitchProdDetailVersion(detail);

            //写入日志
            PadStitchLog log = new PadStitchLog();
            log.setCompanyId(companyId);
            log.setDeptNo(deptNo1);
            log.setDeptName(deptName1);
            log.setSysUser(collectUserName);
            log.setOperationResult(BigDecimal.valueOf(count));
            log.setOperationType("Z");
            log.setOperationTypeName("录入报产");
            // 将StitchInventoryDetailDRequest2对象转换为JSON字符串
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                String operationObjectJson = objectMapper.writeValueAsString(r);
                log.setOperationObject(operationObjectJson);
            } catch (Exception e) {
                throw new  ServiceErrorException("JSON转换失败: " + e.getMessage());
            }
            stitchInventoryMapper.addPadStitchLog(log);

            long executionTime = System.currentTimeMillis() - start;
            System.out.println(executionTime + "ms");

            if(count > 0){
                return ResponseInfo.ok("录入报产成功");
            }else{
                throw  new ServiceErrorException("录入报产失败");
            }
        } finally {
            // 确保无论如何都会释放锁
            unlock(lockKey, lockValue);
        }


    }

    /**
     * 道序合并报产
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo batchReportProcess(StitchInventoryDetailDRequest2 r) {
        long start = System.currentTimeMillis();

        //判断
        List<StitchInventoryDetailDRequest> list = r.getList();
        if(ObjectUtils.isEmpty(list)){
            throw  new ServiceErrorException("请选择数据！");
        }
        if(r.getWorkId() == null || r.getWorkName() == null){
            throw  new ServiceErrorException("请选择员工！");
        }
        //报产的部门不能为空或者空字符串
        if(r.getDeptNo() == null || r.getDeptName() == null || r.getDeptNo().equals("") || r.getDeptName().equals("") ){
            throw  new ServiceErrorException("报产部门不能为空！");
        }

        // 过滤 list，移除 lotNo 为空的元素
        list = list.stream()
                .filter(item -> Objects.nonNull(item.getLotNo()) && !item.getLotNo().trim().isEmpty())
                .collect(Collectors.toList());

        // 检查过滤后的列表是否为空
        if (CollectionUtils.isEmpty(list)) {
            throw new ServiceErrorException("所有选择的数据中没有有效的 LotNo指令，请刷新重试！");
        }

        // 道序报产已经道序合并报产不能自由录入数据，只能录入人员,数量固定是可报数
        PadUserTokenDto padUserTokenDto = PadUserIdThread.get();
        String companyId = padUserTokenDto.getCompanyId();
        String collectUserName = padUserTokenDto.getCollectUserName();
        List<PadUserDeptDto> departmentList = padUserTokenDto.getDepartmentList();
        if(ObjectUtils.isEmpty(departmentList) ){
            throw  new ServiceErrorException("token中没有查到当前登录部门信息") ;
        }
        PadUserDeptDto deptDto = departmentList.get(0);
        String deptNo1 = deptDto.getDeptNo();
        String deptName1 = deptDto.getDeptName();

        //上锁
        StitchInventoryDetailDRequest request1 = list.get(0);
        String lockKey = "lock:stitchProReport:" + companyId + ":" + request1.getLotNo() + ":" +
                request1.getSlipDate() + ":" + request1.getOrderType() + ":" + request1.getDeptNo();
        String lockValue = UUID.randomUUID().toString();

        // 设置锁的有效期为1000毫秒（1秒）（假设最大执行时间为200毫秒）
        boolean isLocked = tryLock(lockKey, lockValue, 5, TimeUnit.SECONDS);

        if (!isLocked) {
            throw new ServiceErrorException("系统繁忙，请稍后刷新后再试");
        }

        try {
            // 执行原有业务逻辑...
            // ...
            //1.第一道检查：检查现在已经报产的总数量和最大的版本号
            List<StitchInventoryDetailDto> countFlagList = stitchInventoryMapper.getNotReportProcessDetailsByLotNo4(companyId,request1);
            // 获取并准备 countFlagMap
            Map<String, Integer> countFlagMap = new HashMap<>();
            for (StitchInventoryDetailDto flagDto : countFlagList) {
                String key = companyId + ":" + flagDto.getLotNo() + ":" + flagDto.getSlipDate() + ":" + flagDto.getOrderType() + flagDto.getDeptNo()  + ":" + flagDto.getProcessName();
                countFlagMap.put(key, flagDto.getQty3());
            }

             // 验证 list 中的数据是否满足条件
            for (StitchInventoryDetailDRequest request1Dto : list) {
                String key = companyId + ":" + request1Dto.getLotNo() + ":" + request1Dto.getSlipDate() + ":" + request1Dto.getOrderType() + request1Dto.getDeptNo() + ":" + request1Dto.getProcessName();
                if(countFlagMap.containsKey(key)){
                    // 第一道检查：检查报产数量
                    int maxQty = countFlagMap.get(key);
                    if ( request1Dto.getQty3() != maxQty ) {
                        throw new ServiceErrorException("数据已更新,请刷新重试");
                    }
                    if ( request1Dto.getQty3() > maxQty ) {
                        throw new ServiceErrorException("数据已更新,报数超出实际,请刷新重试");
                    }

                    // 第二道检查：检查乐观锁
                    //Integer expectedVersion = versionMap.get(key);
                    //if (expectedVersion == null || !expectedVersion.equals(requestDto.getVersion())) {
                    //    throw new ServiceErrorException("数据版本已更新,请刷新重试");
                    //}
                }
            }

            List<PcStitchProdDetail> detailList = new ArrayList<>();
            for (StitchInventoryDetailDRequest request : list) {

                PcStitchProdDetail detail = new PcStitchProdDetail();
                BeanUtils.copyProperties(request,detail);

                BigDecimal price = request.getPrice();//价格
                BigDecimal qty = BigDecimal.valueOf(request.getQty3());//它页面上的可报数
                BigDecimal amt = (price != null) ? qty.multiply(price) : null;//金额
                detail.setQty(qty);
                detail.setPrice(price);
                detail.setAmt(amt);


                detail.setWorkId(r.getWorkId());
                detail.setWorkName(r.getWorkName());
                detail.setWorkDeptNo(r.getDeptNo());
                detail.setWorkDeptName(r.getDeptName());
                detail.setDeptNo(deptNo1);
                detail.setDeptName(deptName1);

//            detail.setSysDate(LocalDateTime.now());
                detail.setSysUser(collectUserName);
                detail.setCfmFlag("Y");
//            detail.setCfmDate(String.valueOf(LocalDateTime.now()));
                detail.setCfmUser(PadUserIdThread.get().getCollectUserName());
                detail.setCompanyId(companyId);
                detail.setSlipDate(request.getSlipDate());
                detail.setSeqNo(BigDecimal.valueOf(request.getSeqNo()));
                if(request.getOrderType2() != null){
                    if (request.getOrderType2().equals("正单")) {
                        detail.setOrderType(BigDecimal.valueOf(0));
                    }else if(request.getOrderType2().equals("补单")){
                        detail.setOrderType(BigDecimal.valueOf(1));
                    }
                }else{
                    throw  new ServiceErrorException("请检查指令类型！");
                }

                detailList.add(detail);
            }

            int count = 0;
            try {
                count = stitchInventoryMapper.addBatchPcStitchProdDetail(detailList);
            }catch(Exception se){
                throw  new ServiceErrorException("请刷新重试");
            }

            //写入日志
            PadStitchLog log = new PadStitchLog();
            log.setCompanyId(companyId);
            log.setDeptNo(deptNo1);
            log.setDeptName(deptName1);
            log.setSysUser(collectUserName);
            log.setOperationResult(BigDecimal.valueOf(count));
            log.setOperationType("Z");
            log.setOperationTypeName("道序合并报产");
            // 将StitchInventoryDetailDRequest2对象转换为JSON字符串
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                String operationObjectJson = objectMapper.writeValueAsString(r);
                log.setOperationObject(operationObjectJson);
            } catch (Exception e) {
                throw new  ServiceErrorException("JSON转换失败: " + e.getMessage());
            }
            stitchInventoryMapper.addPadStitchLog(log);

            long executionTime = System.currentTimeMillis() - start;
            System.out.println(executionTime + "ms");

            if(count > 0){
                return ResponseInfo.ok("道序合并报产成功");
            }else{
                throw  new ServiceErrorException("道序合并报产失败");
            }
        } finally {
            // 确保无论如何都会释放锁
            unlock(lockKey, lockValue);
        }
    }

    /**
     * 已报工序查询
     * @param request
     * @return
     */
    @Override
    public ResponseInfo getReportProcessDetails(StitchInventoryRequest request) {
        String companyId = PadUserIdThread.get().getCompanyId();
        List<StitchInventoryDetailDto> list = stitchInventoryMapper.getReportProcessDetails(companyId,request);

        HashMap map = new HashMap<>();
        PageInfo page = new PageInfo(list);
        map.put("total",page.getTotal());
        map.put("list",list);
        return ResponseInfo.ok(map);
    }

    /**
     * 已经报产工序删除
     * @param request
     * @return
     */
    @Override
    public ResponseInfo deleteReportProcess(StitchInventoryDetailDto request) {
        String companyId = PadUserIdThread.get().getCompanyId();

        //如果现在是12月5号11点39分，要求删除:
        //今天的数据：你可以删除从12月5日00:00到现在的所有数据。
        //昨天的数据：你可以删除从12月4日00:00到23:59的所有数据。

        // 获取今天的日期和昨天的日期
        // 获取今天的日期和昨天的日期，包括时间部分
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime todayStart = now.toLocalDate().atStartOfDay(); // 今天凌晨00:00
        LocalDateTime yesterdayStart = todayStart.minusDays(1); // 昨天凌晨00:00

        // 将sysDate字符串转换为LocalDateTime对象，假设sysDate包含时间和日期
        String sysDate = request.getSysDate();
        LocalDateTime sysDateLocalDateTime;
        try {
            sysDateLocalDateTime = LocalDateTime.parse(sysDate, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        } catch (DateTimeParseException e) {
            throw new ServiceErrorException("日期格式不正确，请检查输入的日期格式！");
        }

        // 检查传入的日期是否为今天或昨天
        if (sysDateLocalDateTime.isBefore(yesterdayStart) || sysDateLocalDateTime.isAfter(now)) {
            String formattedSysDate = sysDateLocalDateTime.format(FORMATTER);
            throw new ServiceErrorException(
                    "只能删除今天或昨天的数据!\n" +
                            "该工序报账时间:" + formattedSysDate + ",已超时!");
        }

        int count = stitchInventoryMapper.deleteReportProcess(companyId, request);

        //写入日志
        PadStitchLog log = new PadStitchLog();
        log.setCompanyId(companyId);
        log.setDeptNo(PadUserIdThread.get().getDepartmentList().get(0).getDeptNo());
        log.setDeptName(PadUserIdThread.get().getDepartmentList().get(0).getDeptName());
        log.setSysUser(PadUserIdThread.get().getCollectUserName());
        log.setOperationResult(BigDecimal.valueOf(count));
        log.setOperationType("S");
        log.setOperationTypeName("已报工序删除");
        // 将StitchInventoryDetailDRequest2对象转换为JSON字符串
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String operationObjectJson = objectMapper.writeValueAsString(request);
            log.setOperationObject(operationObjectJson);
        } catch (Exception e) {
            throw new  ServiceErrorException("JSON转换失败: " + e.getMessage());
        }
        stitchInventoryMapper.addPadStitchLog(log);

        if(count > 0){
            return ResponseInfo.ok("报产工序删除成功");
        }else{
            throw  new ServiceErrorException("报产工序删除失败");
        }
    }
}
